﻿CREATE PROCEDURE [dbo].[users_validate]
    @userId int = 0,
    @login nvarchar(256) = null,
    @email nvarchar(256) = null
AS
DECLARE 
    @valid bit = 0,
    @usersByEmail int =0,
    @usersByLogin int =0

If(@login = @email)
    RETURN @valid

If(@userId = 0)
    BEGIN 
        SELECT @usersByEmail = Count (*)
            FROM Users WHERE Users.Email = @email OR Users.Email = @login
        SELECT @usersByLogin = Count (*)
            FROM Users WHERE [dbo].[Users].[Login] = @login OR [dbo].[Users].[Login] = @email
                
    END
else
    BEGIN
       SELECT @usersByEmail = Count (*)
            FROM Users WHERE (Users.Email = @email OR Users.Email = @login) AND Users.UserId != @userId 
        SELECT @usersByLogin = Count (*)
            FROM Users WHERE ([dbo].[Users].[Login] = @login OR [dbo].[Users].[Login] = @email) AND Users.UserId != @userId
    END

If(@usersByEmail = 0 AND @usersByLogin = 0)
    BEGIN
      SELECT @valid = 1
    END 
RETURN @valid
